<template>
  <div>
    <el-form ref="formRef" :rules="rules" :model="form" label-width="100px">
      <el-form-item label="部门名称" prop="name">
        <el-input v-model="form.name" />
      </el-form-item>
      <el-form-item label="部门编码" prop="code">
        <el-input v-model="form.code" />
      </el-form-item>
      <el-form-item label="部门负责人" prop="manager">
        <el-select v-model="form.manager" placeholder="请选择部门负责人">
          <!-- <el-option label="区域一" value="shanghai" /> -->
          <el-option v-for="item in userList" :key="item.id" :label="item.username" :value="item.username" />
        </el-select>
      </el-form-item>
      <el-form-item label="部门介绍" prop="introduce">
        <el-input v-model="form.introduce" type="textarea" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">{{ isEdit ? '编辑' : '新增' }}</el-button>
        <el-button @click="cancle">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { getUserSimpleRequest } from '@/api/employess'
import { addDepartmentRequest, getDepartmentByIdRequest, updateDepartmentByIdRequest } from '@/api/departments'
// import { checkCode } from '@/utils/validate'

export default {
  props: {
    currentPid: {
      type: String,
      default: ''
    },
    isEdit: {
      type: Boolean,
      default: false
    },
    arrListToChild: {
      type: Array,
      default: () => []
    }
  },
  // form对象里有什么属性，需要后端决定
  data() {
    const validateCode = (rule, value, callback) => {
      // value非空校验
      if (!value) return callback(new Error('部门编码不能为空'))
      let codeList = this.arrListToChild.map(item => item.code)
      // 当点击编辑的时候，当前的code码不算重复
      if (this.isEdit) {
        codeList = this.arrListToChild.filter(item => item.id !== this.currentPid).map(item => item.code)
      }
      if (codeList.includes(value)) {
        callback(new Error('重复的部门编码'))
      } else {
        callback()
      }

      // const res = this.arrListToChild.findIndex(item => item.code === value)
      // if (res === -1) {
      //   callback()
      // } else {
      //   callback(new Error('重复的部门编码'))
      // }
    }
    let nameList = this.arrListToChild.filter(item => item.pid === this.currentPid).map(item => item.name)

    const validatename = (rule, value, callback) => {
      if (this.isEdit) {
        // 先找到当前 需要编辑的元素 当前元素  this.currentPid
        const editParent = this.arrListToChild.find(item => item.id === this.currentPid)
        // 再去找 editParent 所有的兄弟元素， 具体的就是 pid都等于 editParent.pid 的元素
        const brother = this.arrListToChild.filter(item => item.pid === editParent.pid)
        // 因为是编辑，所以最后还需要过滤掉当前的 被编辑的元素
        nameList = brother.filter(item => item.id !== this.currentPid).map(item => item.name)
      }
      if (nameList.includes(value)) {
        callback(new Error('当前部门已经存在'))
      } else {
        callback()
      }
    }
    return {
      form: {
        code: '',
        inroduce: '',
        manager: '',
        name: ''
      },
      userList: [],
      rules: {
        name: [
          { required: true, message: '请输入活动名称', trigger: 'blur' },
          { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' },
          { trigger: 'change', validator: validatename }
        ],
        code: [
          // { required: true, message: '请输入部门编码', trigger: 'blur' },
          { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' },
          { trigger: 'blur', validator: validateCode }

        ],
        manager: [
          { required: true, message: '请输入活动名称', trigger: 'chnage' }
        ],
        introduce: [
          { required: true, message: '请输入活动名称', trigger: 'blur' },
          { min: 2, max: 300, message: '长度在 2 到 300 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    // console.log(this.arrListToChild)
    this.getUserSimple()
    this.getDepartmentById()
  },
  methods: {
    async getUserSimple() {
      try {
        const res = await getUserSimpleRequest()
        // console.log(res)
        this.userList = res.data
      } catch (error) {
        console.log(error)
      }
    },
    cancle() {
      this.$emit('MyCloseEvent')
    },
    // 新增请求
    async addDepartment() {
      try {
        const res = await addDepartmentRequest({ ...this.form, pid: this.currentPid })
        // console.log(res)
        // 抛出一个新的事件，在父组件里面，要将弹出框关闭，也要重新发请求，获取新的树状结构列表
        if (res.success) {
          this.$emit('success')
        } else {
          this.$message.error(res.message)
        }
      } catch (err) {
        console.log(err)
      }
    },
    onSubmit() {
      // 因为点击创建，后面还需要做一些校验，这个代码会有很多，所有
      // 我们需要将 新增的接口请求，封装到外面，作为一个函数
      // console.log(this.form)
      // 调用ele中表单验证的validate方法，来进行兜底校验，没成功的情况下不发请求
      this.$refs.formRef.validate(value => {
        if (value) {
          if (this.isEdit) {
            // 如果是编辑就发编辑的请求
            this.updateDepartmentById()
          } else {
            this.addDepartment()
          }
        }
      })
    },
    // 点击编辑发请求
    async getDepartmentById() {
      if (this.isEdit) {
        const res = await getDepartmentByIdRequest(this.currentPid)
        // console.log(res)
        this.form = res.data
      }
    },
    async updateDepartmentById() {
      await updateDepartmentByIdRequest(this.form)
      this.$emit('success')
    }
  }

}
</script>

<style>

</style>
